<template>
    <div class="padding-xl flex home" style="width: 100%;">
        <div class="flex-sub "  >
            <div v-for="(item, index) in routes" :key="index">
                <div v-if="item.id!==9999" :id="'part'+index" class="padding-top padding-left padding-right">
                    <div style="border-bottom: #e6e6e6 solid 1px;" class="margin-bottom-xs padding-bottom-xs">
                        {{ item.meta.title }}
                    </div>

                    <div class="flex" style="flex-wrap: wrap;">
                        <el-card v-for="(sub, xindex) in item.children" :key="xindex" shadow="hover" class="out-card margin-right margin-bottom-xs">
                            <router-link v-if=" !sub.meta.tag" :to="{path: sub.path }" style="text-decoration: none;">
                                <div class="flex flex-direction align-center homeButton" style="width: 170px;">
                                    <img v-if="sub.meta.launchIcon" style="width: 60px; height: 60px; margin-bottom: 6px;" :src="require('../assets/home/'+sub.meta.launchIcon)">
                                    <img v-else style="width: 50px; height: 50px; margin-bottom: 6px;" src="">
                                    <span>{{ sub.meta.title }}</span>
                                </div>
                            </router-link>
                            <div v-else style="text-decoration: none; cursor: pointer;">
                                <div v-if=" sub.meta.tag==='home'" class="flex flex-direction align-center homeButton" @click="openHome">
                                    <img v-if="sub.meta.launchIcon" style="width: 60px; height: 60px; margin-bottom: 6px;" :src="require('../assets/home/'+sub.meta.launchIcon)">
                                    <img v-else style="width: 50px; height: 50px; margin-bottom: 6px;" src="">
                                    <span>{{ sub.meta.title }}</span>
                                </div>

                                <div v-if=" sub.meta.tag==='shortcut'" class="flex flex-direction align-center justify-center homeButton homeButton2" @click="openShortcut">
                                    <i class="el-icon-plus" />
                                </div>
                            </div>
                        </el-card>
                    </div>
                </div>
            </div>
        </div>
        <div style="width: 200px;">
            <ul id="boxFixed" class="right-menu">
                <template v-for="(item, index) in routes">
                    <li v-if="item.id!==9999" :key="index" style="cursor: pointer;"
                        class="menu-item" :class="currentPart === index? 'is-current' : ''" @click="goPart(index)">
                        <span>{{ item.meta.title }}</span>
                    </li>
                </template>
            </ul>
        </div>

        <el-dialog title="快捷应用" :visible.sync="advancedVisible" width="700px">
            <div style="height: 380px; width: 100%; overflow: auto;">
                <el-row style="margin-bottom: 8px;">
                    快捷应用
                </el-row>
                <el-row style="margin-bottom: 5px;">
                    <draggable v-model="shortcutItems" filter=".el-icon-close" chosen-class="chosen" force-fallback="true" group="people" animation="500">
                        <transition-group>
                            <el-tag
                                v-for="(tag, index) in shortcutItems"
                                :key="'tag'+index"
                                style="margin-right: 10px; margin-bottom: 5px; cursor: move;"
                                closable
                                @close="handleCloseTag(tag)">
                                {{ tag.meta.title }}
                            </el-tag>
                        </transition-group>
                    </draggable>
                </el-row>

                <template v-for="(item, index) in menus">
                    <el-row :key="'row'+index" style="margin-bottom: 8px; margin-top: 10px;">
                        {{ item.meta.title }}
                    </el-row>
                    <el-row :key="index">
                        <el-col v-for="(sub, xindex) in item.children" :key="xindex" :span="6">
                            <el-checkbox v-model="sub.checked"
                                         style="margin-bottom: 5px; color: #72767b;" :true-label="sub.name+'.true'"
                                         :false-label="sub.name+'.false'" @change="checkboxChange">
                                {{ sub.meta.title }}
                            </el-checkbox>
                        </el-col>
                    </el-row>
                </template>
            </div>

            <div slot="footer" class="dialog-footer">
                <el-button size="small" @click="advancedVisible = false">取 消</el-button>
                <el-button size="small" :loading="isLoading" type="primary" @click="handleSaveAdvanced">确 定</el-button>
            </div>
        </el-dialog>
<!--        <el-dialog title="磁盘空间不足" :visible.sync="detailVisible"  width="800px">-->
<!--            <h1>剩余空间还有：{{msg.disk}}G</h1>-->
<!--            <el-button size="mini" type="primary" plain-->
<!--                       @click="btnok">-->
<!--                关闭-->
<!--            </el-button>-->

<!--        </el-dialog>-->
    </div>
</template>

<script>
import store from '@/store';
import { Base64 } from 'js-base64/base64';
import { deepClone } from '@/util';
import draggable from 'vuedraggable';
// import { WarningDiskCapacity } from '@/api/login';

export default {
    name: 'dashboard',
    components: {
        draggable
    },
    data() {
        return {
            currentPart: 0,
            advancedVisible: false,
            shortcutItems: [],
            isLoading: false,
            shortcuts: [],
            detailVisible: false,
            msg: {
                disk: 1000
            }
        };
    },
    computed: {
        shortcutKey: function() {
            return 'shortcut_' + this.$store.state.user.account;
        },
        routes: function() {
            let items = [...this.$store.state.menu.routes];
            items.splice(0, 1);

            items.unshift({
                meta: {
                    title: '快捷应用'
                },
                children: [...this.shortcuts, {
                    meta: {
                        tag: 'shortcut'
                    }
                }]
            });
            console.log("items");
            console.log(items);
            return items;
        },
        menus: function() {
            let items = deepClone(this.$store.state.menu.routes);
            items.splice(0, 1);
            return items;
        },
        menuMap: function() {
            let map = {};
            this.menus.forEach(item => {
                item.children.forEach(menu => {
                    map[menu.name] = {
                        name: menu.name,
                        path: menu.path,
                        meta: {
                            title: menu.meta.title,
                            launchIcon: menu.meta.launchIcon,
                            tag: menu.meta.tag
                        }
                    };
                });
            });
            return map;
        }
    },
    mounted() {
        window.addEventListener('scroll', this.handleScroll);

        let jsonString = localStorage[this.shortcutKey];
        if (jsonString) {
            let json = JSON.parse(jsonString);
            if (json) {
                this.shortcuts = json;
            }
        }
        // WarningDiskCapacity().then(res => {
        //     if (res.res.WarningDiskCapacity < 500) {
        //         this.msg.disk = res.res.WarningDiskCapacity;
        //         this.detailVisible = true;
        //     }
        // }).catch(err => {
        //     console.log(err);
        // });
    },
    methods: {
        openHome() {
            let data = {
                AutoLogin: store.state.user.token,
                LoginName: store.state.user.account
            };
            let ticket =  Base64.encode(JSON.stringify(data));
            window.open(GlobalConfig.dataviewBaseurl + '?ticket=' + encodeURIComponent(ticket), '_blank');
        },
        goPart(index) {
            this.currentPart = index;
            let anchor = this.$el.querySelector('#part' + index);
            document.body.scrollTop = anchor.offsetTop + 1;
            document.documentElement.scrollTop = anchor.offsetTop + 1;
        },
        handleScroll() {
            // console.log('handleScroll');
            let offset = 0;
            let scrollTop = (window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop) - offset;
            let length = this.routes.length;
            for (let i = 0; i < length ; i++) {
                let partOffset1 = this.$el.querySelector('#part' + i).offsetTop;
                let partOffset2 = ((i + 1) < length) ? this.$el.querySelector('#part' + (i + 1)).offsetTop : 99999;

                // console.log('scrollTop:',scrollTop,'partOffset'+i+':',partOffset1,'partOffset'+(i+1)+':',partOffset2);

                if (scrollTop <= partOffset1) {
                    // console.log('<partOffset1');
                    this.currentPart = i;
                    break;
                } else if (scrollTop > partOffset1 && scrollTop < partOffset2) {
                    this.currentPart = i;
                    // console.log('break');
                    break;
                }
            }
        },
        openShortcut() {
            this.advancedVisible = true;

            this.shortcutItems = [...this.shortcuts];
            this.menus.forEach(item => {
                item.children.forEach(menu => {
                    if (
                        this.shortcutItems.some(r => {
                            return r.name === menu.name;
                        })
                    ) {
                        menu.checked = menu.name + '.true';
                    } else {
                        menu.checked = menu.name + '.false';
                    }
                });
            });

        },
        checkboxChange(val) {
            console.log('checkboxChange', val);
            let arr = val.split('.');
            if (arr && arr.length === 2) {
                let key = arr[0];
                let checked = arr[1];
                if (checked === 'true') {
                    let menu = this.menuMap[key];
                    if (menu) {
                        this.shortcutItems.push(menu);
                    }
                } else {
                    let index = this.shortcutItems.findIndex(menu => {
                        return menu.name === key;
                    });
                    this.shortcutItems.splice(index, 1);
                }
            }
        },
        handleCloseTag(tag) {
            console.log('handleCloseTag');
            let key = tag.name;
            let index = this.shortcutItems.findIndex(menu => {
                return menu.name === key;
            });
            this.shortcutItems.splice(index, 1);

            this.menus.forEach(item => {
                item.children.forEach(menu => {
                    if (menu.name === key) {
                        menu.checked = false;
                    }
                });
            });

        },
        handleSaveAdvanced() {
            let jsonString = JSON.stringify(this.shortcutItems);
            localStorage.setItem(this.shortcutKey, jsonString);
            this.shortcuts = [...this.shortcutItems];
            this.advancedVisible = false;
        },
        btnok() {
            this.detailVisible = false;
        }
    }
};
</script>

<style lang="scss" scoped>

.home {
    //background: url("../assets/images/home-bg.png") no-repeat;
    //background-attachment: fixed;
}
.out-card {
    ::v-deep .el-card__body {
        padding: 0;
    }
}
.chosen {
    border-width: 2px;
    border-color: #409eff;
}
.right-menu {
    list-style-type: none;
    position: fixed;
    top: 156px;
    padding-left: 0;
    z-index: 10;
    border-left: 1px solid #dcdfe6;
    .menu-item {
        margin-left: -10px;
        padding: 6px 25px;
        &:hover {
            color: #f1c40f;
            font-size: 18px;
        }
    }
}
.is-current {
    font-size: 18px;
    color: #3a8ee6;
    background: url("../assets/home/icon_li_current.png") no-repeat;
    background-size: 18px 18px;
    background-position: 0 10px;
}
.fa-info {
    padding: 10px 0 0;
    text-align: center;
    h1 {
        margin: 10px auto 20px;
    }
}
.homeButton {
    line-height: 1;
    white-space: nowrap;
    cursor: pointer;
    background: #fff;
    color: #606266;
    -webkit-appearance: none;
    text-align: center;
    box-sizing: border-box;
    outline: none;
    margin: 0;
    transition: 0.1s;
    font-weight: 500;
    -moz-user-select: none;
    -webkit-user-select: none;
    -ms-user-select: none;
    width: 130px;
    height: 120px;
    padding-top: 17px;
    font-size: 14px;
    &:hover {
        background: #f0f7ff;
    }
}
.homeButton2 {
    font-size: 50px;
    color: #cccfd6;
    padding-top: 0;
    border-radius: 4px;
    &:hover {
        color: #3a8ee6;
    }
}
</style>
